class SchoolsController < ApplicationController
  before_filter :set_nav_session
  before_filter :login_required, :except => [:index, :recent, :all, :show, :search, :unconfirmed, :confirmed, :requirements, :archives, :show_date]
  before_filter :unread_messages_amount, :only => [:index, :unconfirmed, :confirmed,
                                                   :requirements, :all_comments, :new,
                                                   :new_camp, :new_board, :edit, :show]
  
  
  def index
    @validated_schools = School.valid
    @photos = Photo.all
    @comments = SchoolComment.all   
    #@visiteds = Visited.all
    get_school_requirements
    @provinces, @output = sort_by_province(1)
  end
  
  def unconfirmed
    @provinces, @output = sort_by_province(0)
  end
  
  def confirmed
    @provinces, @output = sort_by_province(1)
  end

  def search
    @keyword = params[:target]
    if @keyword
      tokens = params[:target].split.collect {|c| "%#{c}%"}
      areas = Area.find_by_sql(["select * from areas where #{(["title like ?"] * tokens.size).join(" and ")}", *tokens])
      areas = (areas.collect{|a| a.all_children} + areas).flatten
      @schools =School.find(:all, :conditions => ["is_hidden=? and is_validate=1 and area_id in(?)", false, areas], :include => :submitor)
    end
  end
  
  def requirements
    redirect_back_or_default(schools_path) if params[:name].empty?
    @schools = School.find_tagged_with(params[:name])
    provinces = Area.roots
    all_provinces = []
    output = []
    provinces.each do |province|
      areas = province.all_children
      area_ids = areas.collect{|a| a.id}
      unless areas.empty?
        ss = @schools.find_all{|school| area_ids.include?(school.area_id) }
        output[province.id] = ss unless ss.empty?
      end
    end
    provinces.each do |province|
      unless output[province.id].blank?
        all_provinces << province
      end
    end
    @provinces = all_provinces
    @output = output
    get_school_requirements(20)
  end
  
  def all_comments
    # @comments = SchoolComment.find(:all, :order => "school_comments.created_at desc", :include => :user)
    @comments = SchoolComment.paginate(:per_page => 10, :page => params[:page], :order => "school_comments.created_at DESC", :include => :user)
  end
  
  def new
    @content_title = "提交新的学校信息"
    @school = School.new(:area_id => params[:area], :info_source => params[:ref])
  end
  
  def new_camp
    @content_title = "提交帐篷学校信息"
    @school = School.new(:edu_type => 3, :info_source => 'dizhen.1kg.org') # 临时安置点，帐篷学校
    render "/schools/new"
  end
  
  def new_board
    @content_title = "提交板房学校信息"
    @school = School.new(:edu_type => 3) # 板房学校
    render "/schools/new"
  end
  
  def create
    @school = School.new(params[:school])
    @school.submitor = current_user
    @school.tag_list = new_tag_list(@school)
    @school.is_meta = false
    @school.save!
    flash[:notice] = "谢谢你提交的学校信息，在多背一公斤学校管理小组认证之前你还可以进行编辑"
    redirect_back_or_default(school_path(@school))
  rescue ActiveRecord::RecordInvalid
    render :action => "new"
  end

  def edit
    @school = School.find(params[:id])
    @school.editable_by?(self.current_user) || access_denied
  end
  
  def update
    @school = School.find(params[:id])
    @school.editable_by?(self.current_user) || access_denied
    @school.tag_list = new_tag_list(params[:school])
    
    # 完善学校资料
    if @school.is_meta?
      @school.is_meta = false
      @school.submitor = current_user
    end
    
    @school.update_attributes!(params[:school])
    flash[:notice] = "你刚刚编辑了#{@school.title}的资料"
    redirect_back_or_default(school_path(@school))
  rescue ActiveRecord::RecordInvalid
    render :action => "edit"
  end
  
  def destroy
    @school = School.find(params[:id])
    @school.update_attributes!(:is_hidden => true)
    flash[:notice] = "您将 #{@school.title} 移到了回收站"
    redirect_back_or_default(schools_path)
  end

  def show
    @school = School.find(params[:id], :conditions => {:is_hidden => false})
    @photos = @school.photos.find(:all, :order => "created_at desc")
    @travelers = @school.travelers.find(:all, :order => "visit_at desc")
    @students = @school.students
    
    @comments = @school.comments
    @comment = SchoolComment.new
    
    #store_location
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "没有找到你查找的学校"
    redirect_to schools_path
  end
  
  # 给出指定日期的所有学校
  def show_date
    if params[:valid] == "false"
      @schools = School.show_date(params[:year],params[:month],params[:day],false)
      render :template => "schools/show_invalid"
    else
      @schools = School.show_date(params[:year],params[:month],params[:day],true)
      render :template => "schools/show_valid"
    end 
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "没有找到你查找的学校"
    redirect_to schools_path
  end
  
  # PUT /schools/:id;validate 
  def validate
    @school = School.find(params[:id])
    @school.update_attributes!(:is_validate => !@school.is_validate)
    if @school.is_validate
      flash[:notice] = "#{@school.title} 已通过验证"
    else
      flash[:notice] = "#{@school.title} 已取消验证"
    end
    redirect_back_or_default(school_path(@school))
  end

  # PUT /schools/:id;visit
  def visit
    @school = School.find(params[:id])
    if @visited = Visited.find(:first, :conditions => {:school_id => @school.id, :user_id => current_user.id})
      @visited.update_attributes!(params[:visited])
    else
      @visited = Visited.new(params[:visited])
      @visited.traveler = current_user
      @visited.school = @school
      @visited.save!
    end
    redirect_back_or_default(school_path(@school.id))
  end
  
  # only for imgrate school data
    def build_tag_list
      @schools = School.find :all
      @schools.each do |s|
        s.tag_list = new_tag_list(s)
        s.save(false)
      end
      flash[:notice] = "Build tag list successfully"
    end
    
  def archives
  end
    
  private
  def new_tag_list(school)
    new_tag_list = ""
    %w(urgency_need books_need stationaries_need sports_need clothes_need accessories_need others_need classes_need teachers_need).each do |attr|
      new_tag_list += school[attr.to_sym] unless school[attr.to_sym].nil?
    end
    new_tag_list
  end
  
  # TODO: better performance
  def set_nav_session
    session[:nav] = "schools"
  end
  
  def sort_by_province(is_validate=1)
    provinces     = Area.roots
    all_provinces = []
    output        = []

    provinces.each do |province|
      areas = province.all_children
      unless areas.empty?
        schools = School.find(:all, 
                              :conditions => ["schools.is_hidden=? and schools.is_validate=? and schools.area_id in (?)", false, is_validate, areas], 
                              :joins => "left join users on schools.submitor_id = users.id",
                              :select => "schools.id, schools.title, schools.updated_at, schools.is_validate,
                                          schools.title, schools.submitor_id, users.login",
                              :order => "schools.area_id asc, schools.created_at desc")
        unless schools.empty?
          output[province.id] = schools
        end
      end
    end
    provinces.each do |province|
      unless output[province.id].blank?
        all_provinces << province
      end
    end
    
    return all_provinces, output
  end
  
  def get_school_requirements(count=50)
    @tags = School.tag_counts.sort{|a,b| b.count <=> a.count}.slice(0,count).sort_by{rand}
  end
end
